package com.exceeddata.vcloud.business.scheduling.impl;

import java.util.Date;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.exceeddata.vcloud.business.domain.dto.SchedulingJobInfoDto;
import com.exceeddata.vcloud.business.scheduling.QuartzSchedulingService;
import com.exceeddata.vcloud.business.scheduling.job.QuartzSchedulingJob;
import com.exceeddata.vcloud.common.exception.ServiceRunTimeException;
import com.exceeddata.vcloud.common.tools.StringTool;

@Service
public class QuartzSchedulingServiceImpl implements QuartzSchedulingService {

	@Autowired
	private Scheduler scheduler;
	
	/**
	 * 描述: 创建定时调度任务
	 * 创建人: 赵兴炎
	 * 日期: 2023年05月23日
	 */
	@Override
	public void createSchedulingTaskJob(SchedulingJobInfoDto schedulingJobInfo) {
		// 获取任务唯一标识
		String jobId = schedulingJobInfo.getJobId();
		if(jobId == null || jobId.trim().length() == 0) {
			throw new ServiceRunTimeException("任务唯一标识不能为空");
		}
		// 获取定时调度表达式
		String cron = schedulingJobInfo.getCron();
		if(cron == null || cron.trim().length() == 0) {
			throw new ServiceRunTimeException("定时调度corn表达式不能为空");
		}
		try {
			// 设置任务执行类
			JobBuilder jobBuilder = JobBuilder.newJob(QuartzSchedulingJob.class);
			// 设置任务的名称和分组
			JobDetail jobDetail = jobBuilder.withIdentity(jobId, jobId).build();
			// 校验任务是否存在
			boolean checkExists = scheduler.checkExists(jobDetail.getKey());
			if(checkExists)throw new ServiceRunTimeException("任务已经存在:"+jobId);
			// 配置任务调度器
			TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
			triggerBuilder.withIdentity(jobId, jobId);
			// 配置定时调度表达式
			Trigger cronTrigger = triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing()).build();
			scheduler.scheduleJob(jobDetail, cronTrigger);
			scheduler.start();
		} catch (Exception exception) {
			throw new ServiceRunTimeException("创建任务异常:"+jobId,StringTool.exceptionToString(exception));
		}
	}

	/**
	 * 描述: 停止定时调度任务
	 * 创建人: 赵兴炎
	 * 日期: 2023年05月23日
	 */
	@Override
	public void stopSchedulingTaskJob(String jobId) {
		try {
			scheduler.pauseTrigger(TriggerKey.triggerKey(jobId, jobId));
		} catch (Exception exception) {
			throw new ServiceRunTimeException("停止任务异常:"+jobId,StringTool.exceptionToString(exception));
		}		
	}

	/**
	 * 描述: 启动定时调度任务
	 * 创建人: 赵兴炎
	 * 日期: 2023年05月23日
	 */
	@Override
	public void startSchedulingTaskJob(String jobId) {
		try {
			scheduler.resumeTrigger(TriggerKey.triggerKey(jobId, jobId));
		} catch (Exception exception) {
			throw new ServiceRunTimeException("启动任务异常:"+jobId,StringTool.exceptionToString(exception));
		}
	}
	
    /**
     * 描述: 删除任务
     * 创建人: 赵兴炎
     * 日期: 2023年05月23日
     */
	@Override
	public void deleteSchedulingTaskJob(String jobId) {
		try {
			TriggerKey triggerKey = TriggerKey.triggerKey(jobId, jobId);
			scheduler.pauseTrigger(triggerKey);//暂停触发器
			scheduler.unscheduleJob(triggerKey);//移除触发器
			scheduler.deleteJob(JobKey.jobKey(jobId, jobId));//删除Job
		} catch (Exception exception) {
			throw new ServiceRunTimeException("删除任务异常:"+jobId,StringTool.exceptionToString(exception));
		}
	}

    /**
     * 描述: 任务执行一次
     * 创建人: 赵兴炎
     * 日期: 2023年05月23日
     */
	@Override
	public void exectionSchedulingTaskJobOne(String jobId) {
		try {
			jobId = jobId+"-"+new Date().getTime();
			JobBuilder jobBuilder = JobBuilder.newJob(QuartzSchedulingJob.class);
			jobBuilder.withIdentity(jobId, jobId);
			JobDetail jobDetail = jobBuilder.build();
			TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
			triggerBuilder.withIdentity(jobId, jobId);
			triggerBuilder.startAt(new Date());
			triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(10).withRepeatCount(0));
			Trigger trigger = triggerBuilder.build();
			scheduler.scheduleJob(jobDetail, trigger);	
		} catch (Exception exception) {
			throw new ServiceRunTimeException("任务执行失败:"+jobId,StringTool.exceptionToString(exception));
		}
	}

    /**
     * 描述: 校验任务是否存在
     * 创建人: 赵兴炎
     * 日期: 2023年05月23日
     */
	@Override
	public boolean checkSchedulingTaskJob(String jobId) {
		boolean checkExists = false;
		try {
			// 设置任务执行类
			JobBuilder jobBuilder = JobBuilder.newJob(QuartzSchedulingJob.class);
			// 设置任务的名称和分组
			JobDetail jobDetail = jobBuilder.withIdentity(jobId, jobId).build();
			// 校验任务是否存在
			checkExists = scheduler.checkExists(jobDetail.getKey());
			if(checkExists)throw new ServiceRunTimeException("任务已经存在:"+jobId);	
		} catch (Exception exception) {
			throw new ServiceRunTimeException("启动任务失败",StringTool.exceptionToString(exception));	
		}
		return checkExists;
	}

}
